package com.lianxi.Courses.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.DictConstant;
import com.lianxi.Courses.constant.StatusConstant;
import com.lianxi.Courses.dao.*;
import com.lianxi.Courses.entity.*;
import com.lianxi.Courses.exception.CourseExistException;
import com.lianxi.Courses.exception.FileUploadErrorException;
import com.lianxi.Courses.exception.RequestParameterErrorException;
import com.lianxi.Courses.service.CourseService;
import com.lianxi.Courses.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;


    @Override
    public void addCourse(String courseName, String courseInfo, String author,
                          CommonsMultipartFile file, String recommendationGrade,
                          String courseTypeId, HttpSession session)
            throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {

        // 1. 校验请求参数是否为空
        if (ParameterUtil.isNull(courseName) || ParameterUtil.isNull(courseInfo) ||
                ParameterUtil.isNull(author) || file.isEmpty() ||
                ParameterUtil.isNull(courseTypeId) || ParameterUtil.isNull(recommendationGrade)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 2. 创建课程查询条件对象
        CourseExample example = new CourseExample();
        // 3. 构建查询条件：课程名称和课程类型ID必须同时匹配
        example.or()
                .andCourseNameEqualTo(courseName)
                .andCourseTypeIdEqualTo(Integer.parseInt(courseTypeId));
        // 4. 执行数据库查询，检查是否已存在相同课程
        List<Course> courses = courseMapper.selectByExample(example);
        // 5. 如果查询结果不为空，说明课程已存在，抛出异常
        if (!courses.isEmpty()) {
            throw new CourseExistException("该课程已经存在");
        }

        // 6. 获取当前时间作为课程创建时间
        Date createDate = new Date();
        // 7. 创建课程对象
        Course course = new Course();
        // 8. 设置课程基本信息
        course.setCourseName(courseName);          // 课程名称
        course.setCourseInfo(courseInfo);          // 课程简介
        course.setAuthor(author);                  // 作者
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade)); // 推荐等级
        course.setCourseTypeId(Integer.parseInt(courseTypeId)); // 课程类型ID
        course.setCreateDate(createDate);          // 创建时间
        course.setClickNumber(0);                  // 初始化点击量为0
        course.setStatus(0);                       // 设置课程状态为0（可能是未发布/启用状态）

        // 9. 处理文件上传
        String filename = file.getOriginalFilename(); // 获取上传文件的原始文件名
        // 10. 按日期创建文件夹路径：格式为 yyyyMMdd
        String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
        // 11. 构建相对路径：/upload/course/20251019/
        String relativePath = "/upload/course/" + dateFolder;

        // 12. 获取服务器上的真实物理路径
        String realPath = session.getServletContext().getRealPath(relativePath);
        // 13. 创建目录对象
        File dir = new File(realPath);
        // 14. 如果目录不存在，则创建目录（包括父目录）
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 15. 构建完整的文件存储路径（相对路径）
        String path = relativePath + "/" + filename;
        // 16. 将文件路径设置到课程对象中
        course.setCoverImageUrl(path);

        try {
            // 17. 将课程信息插入数据库
            courseMapper.insertSelective(course);
            // 18. 创建目标文件对象
            File targetFile = new File(dir, filename);
            // 19. 将上传的文件传输到目标位置
            file.transferTo(targetFile);
        } catch (Exception e) {
            // 20. 如果插入数据库或文件上传失败，抛出文件上传错误异常
            throw new FileUploadErrorException("添加课程失败");
        }
    }

//    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
//    @Override
//    public PageInfo<Course> findPage(String pageNo, String pageSize) {
//        if (ParameterUtil.isNull(pageNo)) {
//            pageNo = DictConstant.COURSE_DEFAULT_PAGE_NO;
//        }
//        if (ParameterUtil.isNull(pageSize)) {
//            pageSize = DictConstant.COURSE_DEFAULT_PAGE_SIZE;
//        }
//        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
//        List<Course> courses = courseMapper.selectAll();
//        PageInfo<Course> coursePage = new PageInfo<>(courses);
//
//        // 如果访问时,当前页没有数据且当前页不是第一页,则返回上一页
//        if (!"1".equals(pageNo) && coursePage.getList().isEmpty()) {
//            Integer page = Integer.parseInt(pageNo) - 1;
//            coursePage = findPage(page + "", pageSize);
//        }
//        return coursePage;
//    }


    //根据参数查询课程列表
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Course> findPage(Course courseParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.COURSE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.COURSE_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Course> courses = courseMapper.selectAll(courseParam);

        for (Course course : courses) {
            CourseExample example = new CourseExample();
            example.or().andIdEqualTo(course.getId());
            List<Course> courses2 = courseMapper.selectByExample(example);
            course.setClickNumber(courses2.size());
        }

        PageInfo<Course> coursePage = new PageInfo<>(courses);
        return coursePage;
    }


    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Course findById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        return courseMapper.selectByPrimaryKey(Integer.parseInt(id));
    }

    @Override
    public void modifyCourse(String id, String courseName, String courseInfo, String author, CommonsMultipartFile file, String recommendationGrade, String courseTypeId, HttpSession session) throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(courseName) || ParameterUtil.isNull(courseInfo) || ParameterUtil.isNull(author) || ParameterUtil.isNull(courseTypeId) || ParameterUtil.isNull(recommendationGrade)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        CourseExample example = new CourseExample();
        example.or()
                .andCourseNameEqualTo(courseName)
                .andCourseTypeIdEqualTo(Integer.parseInt(courseTypeId))
                .andIdNotEqualTo(Integer.parseInt(id));
        List<Course> courses = courseMapper.selectByExample(example);
        if (!courses.isEmpty()) {
            throw new CourseExistException("该课程已经存在");
        }

        Course oldCourse = courseMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (oldCourse == null) {
            throw new RequestParameterErrorException("课程不存在");
        }

        Course course = new Course();
        course.setId(Integer.parseInt(id));
        course.setCourseName(courseName);
        course.setCourseInfo(courseInfo);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade));
        course.setCourseTypeId(Integer.parseInt(courseTypeId));
        course.setCreateDate(oldCourse.getCreateDate());
        course.setClickNumber(oldCourse.getClickNumber());
        course.setStatus(oldCourse.getStatus());
        if (file != null && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String relativePath = "/upload/course/" + dateFolder;
            String realPath = session.getServletContext().getRealPath(relativePath);
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String path = relativePath + "/" + filename;
            course.setCoverImageUrl(path);

            try {
                courseMapper.updateByPrimaryKeySelective(course);
                file.transferTo(new File(realPath, filename));
                if (oldCourse.getCoverImageUrl() != null) {
                    String oldRealPath = session.getServletContext().getRealPath(oldCourse.getCoverImageUrl());
                    File oldFile = new File(oldRealPath);
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }
                }
            } catch (IOException e) {
                throw new FileUploadErrorException("上传课程图片失败");
            }
        } else {

            course.setCoverImageUrl(oldCourse.getCoverImageUrl());
            courseMapper.updateByPrimaryKeySelective(course);
        }
    }


    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(status)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Course course = new Course();
        course.setId(Integer.parseInt(id));
        course.setStatus(Integer.parseInt(status));
        if (course.getStatus() == StatusConstant.COURSE_STATUS_ENABLED) {
            course.setStatus(StatusConstant.COURSE_STATUS_DISABLED);
        } else {
            course.setStatus(StatusConstant.COURSE_STATUS_ENABLED);
        }
        courseMapper.updateByPrimaryKeySelective(course);
    }

    @Override
    public List<Course> findByCourseTypeId(String courseTypeId) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(courseTypeId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        CourseExample example = new CourseExample();
        example.or().andCourseTypeIdEqualTo(Integer.parseInt(courseTypeId));
        return courseMapper.selectByExample(example);
    }

    @Override
    public Course findByIdAll(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }


        Course course = courseMapper.selectByPrimaryKey(Integer.valueOf(id));
        //点击量加1
        course.setClickNumber(course.getClickNumber()+1);
        courseMapper.updateByPrimaryKeySelective(course);
        //章节
        ChapterExample chapterExample = new ChapterExample();
        chapterExample.or()
                .andCourseIdEqualTo(Integer.valueOf(id));
        List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);

        //章节的资源
        ResourceExample resourceExample = new ResourceExample();
        for (Chapter chapter:chapters){
            resourceExample.clear();
            resourceExample.or()
                    .andChapterIdEqualTo(chapter.getId());
            List<Resource> resources = resourceMapper.selectByExample(resourceExample);

            //资源的评论
            for (Resource resource:resources){
                CommentExample commentExample =new CommentExample();
                commentExample.or()
                        .andResourceIdEqualTo(resource.getId());
                List<Comment> comments =commentMapper.selectByExample(commentExample);
                //添加评论
                resource.setComments(comments);
            }

            //添加资源
            chapter.setResources(resources);
        }

        //添加章节
        course.setChapters(chapters);

        //查第三层的课程类别
        CourseType courseType03 =courseTypeMapper.selectByPrimaryKey(course.getCourseTypeId());
        //第二层
        CourseType courseType02 =courseTypeMapper.selectByPrimaryKey(courseType03.getParentId());
        //第一层
        CourseType courseType01 =courseTypeMapper.selectByPrimaryKey(courseType02.getParentId());

        course.setCourseType03(courseType03);
        course.setCourseType02(courseType02);
        course.setCourseType01(courseType01);

        return course;
    }

//    @Override
//    public List<Course> findByTypeId(String courseTypeId) throws RequestParameterErrorException {
//        if (ParameterUtil.isNull(courseTypeId)){
//            throw new RequestParameterErrorException("请求参数有误");
//        }
//
//        CourseExample courseExample =new CourseExample();
//        courseExample.or()
//                .andCourseTypeIdEqualTo(Integer.valueOf(courseTypeId));
//        List<Course> coursesAll =courseMapper.selectByExample(courseExample);
//
//        for (int i = 0; i < coursesAll.size() - 1; i++) {
//            for (int j = i + 1; j < coursesAll.size(); j++) {
//                if (coursesAll.get(i).getClickNumber() < coursesAll.get(j).getClickNumber()) {
//                    // 交换位置
//                    Course temp = coursesAll.get(i);
//                    coursesAll.set(i, coursesAll.get(j));
//                    coursesAll.set(j, temp);
//                }
//            }
//        }
//        List<Course> courses =new ArrayList<>();
//        if (coursesAll.size()>=3){
//            for (int i = 0; i < 3; i++) {
//                courses.add(coursesAll.get(i));
//            }
//        }else {
//            for (int i = 0; i < coursesAll.size(); i++) {
//                courses.add(coursesAll.get(i));
//            }
//        }
//
//        return courses;
//    }







    @Override
    public List<Course> findByTypeId(String courseTypeId) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(courseTypeId)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        CourseExample courseExample =new CourseExample();
        courseExample.or()
                .andCourseTypeIdEqualTo(Integer.valueOf(courseTypeId));
        List<Course> coursesAll =courseMapper.selectByExample(courseExample);

        // 按点击量降序排序
        for (int i = 0; i < coursesAll.size() - 1; i++) {
            for (int j = i + 1; j < coursesAll.size(); j++) {
                if (coursesAll.get(i).getClickNumber() < coursesAll.get(j).getClickNumber()) {
                    // 交换位置
                    Course temp = coursesAll.get(i);
                    coursesAll.set(i, coursesAll.get(j));
                    coursesAll.set(j, temp);
                }
            }
        }

        // 改为返回前4个课程
        List<Course> courses =new ArrayList<>();
        if (coursesAll.size()>=4){
            for (int i = 0; i < 4; i++) {
                courses.add(coursesAll.get(i));
            }
        }else {
            for (int i = 0; i < coursesAll.size(); i++) {
                courses.add(coursesAll.get(i));
            }
        }

        return courses;
    }








    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<Course> getAllCourses() throws RequestParameterErrorException {
        // 获取所有课程
        List<Course> allCourses = courseMapper.selectAll();

        // 按点击量从小到大排序
        for (int i = 0; i < allCourses.size() - 1; i++) {
            for (int j = i + 1; j < allCourses.size(); j++) {
                if (allCourses.get(i).getClickNumber() > allCourses.get(j).getClickNumber()) {
                    // 交换位置
                    Course temp = allCourses.get(i);
                    allCourses.set(i, allCourses.get(j));
                    allCourses.set(j, temp);
                }
            }
        }

        return allCourses;
    }
















    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Course> findPageByExample(CourseExample example, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.COURSE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.COURSE_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Course> courses = courseMapper.selectByExample(example);


        for (Course course : courses) {
            CourseExample example2 = new CourseExample();
            example2.or().andIdEqualTo(course.getId());
            List<Course> courses2 = courseMapper.selectByExample(example2);
            course.setClickNumber(courses2.size());
        }

        PageInfo<Course> coursePage = new PageInfo<>(courses);
        return coursePage;
    }





































}





































































































